package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.AboveTheQuotaApplyDao;
import com.wing.cabinet.dao.MailInfo;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.AboveTheQuotaApplyForm;
import com.wing.cabinet.model.request.AboveTheQuotaApplyProductForm;
import com.wing.cabinet.model.response.AboveTheQuotaApplyProductVO;
import com.wing.cabinet.model.response.AboveTheQuotaApplyVO;
import com.wing.cabinet.utils.MailSenderConfig;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.RSAUtils;
import com.wing.common.utils.Result;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductPackVO;
import com.wing.order.dao.DynamicDao;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 超额申请表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class AboveTheQuotaApplyServiceImpl extends ServiceImpl<AboveTheQuotaApplyDao, AboveTheQuotaApply> implements AboveTheQuotaApplyService {
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private AboveTheQuotaApplyProductService aboveTheQuotaApplyProductService;
    @Autowired
    private CountQuotaService countQuotaService;
    @Autowired
    private AuthorityManageService authorityManageService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private CabinetService cabinetService;
    @Autowired
    private CellInventorySpaceService cellInventorySpaceService;
    @Autowired
    private AuthorityMaterielService authorityMaterielService;
    @Resource
    private JavaMailSender javaMailSender;
    @Autowired
    private MailInfo mailInfo;
    @Autowired
    MailSenderConfig senderConfig;
    @Autowired
    private AuthorityMemberService authorityMemberService;

    @Override
    public int add(AboveTheQuotaApplyForm aboveTheQuotaApplyForm) {

        //校验

        AboveTheQuotaApply aboveTheQuotaApply =new AboveTheQuotaApply();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(AboveTheQuotaApply.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(aboveTheQuotaApplyForm, aboveTheQuotaApply, copyOptions);

        return baseMapper.insert(aboveTheQuotaApply);
    }

    @Override
    public List<AboveTheQuotaApplyVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<AboveTheQuotaApplyVO> pageList4app(Page page, Map<String, Object> params) {
        List<AboveTheQuotaApplyVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public AboveTheQuotaApplyVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }
    @Transactional
    @Override
    public void submitAboveTheQuotaApplyForm(AboveTheQuotaApplyForm aboveTheQuotaApplyForm, String domain) {
        //查询权限组 修改实际授信额度
        AuthorityManage authorityManage = authorityManageService.getById(aboveTheQuotaApplyForm.getAuthorityManageId());
        if(null == authorityManage.getExcessAuditor()){
            throw new BusinessException("当前用户所在权限组未设置超额审核人员");
        }
        QueryWrapper<AuthorityMember> authorityMemberQueryWrapper = new QueryWrapper<>();
        authorityMemberQueryWrapper.eq("authority_manage_id", authorityManage.getId());
        authorityMemberQueryWrapper.eq("user_id", JwtUtils.getLoginUserId());
        AuthorityMember authorityMember = authorityMemberService.getOne(authorityMemberQueryWrapper);
        if(null == authorityMember){
            throw new BusinessException("超额申请记录审核失败:申请人不在该权限组! 权限组名称:" + authorityManage.getName());
        }
        //超额总金额
        BigDecimal total = new BigDecimal(0);
        //超额领新产品的剩余总金额
        //BigDecimal countQuoTotal = new BigDecimal(0);
        AboveTheQuotaApply aboveTheQuotaApply =new AboveTheQuotaApply();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(AboveTheQuotaApply.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(aboveTheQuotaApplyForm, aboveTheQuotaApply, copyOptions);
        aboveTheQuotaApply.setEnterpriseCode(JwtUtils.getEnterpriseCode());
        aboveTheQuotaApply.setCreatorName(JwtUtils.getLoginUsername());
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        Integer maxCode = dynamicDao.getDayMaxNo("ord_above_the_quota_apply");
        String code = CodeUtil.getCode(maxCode);
        aboveTheQuotaApply.setCode("LD" + today + code);
        aboveTheQuotaApply.setNo(Integer.valueOf(code));
        aboveTheQuotaApply.setCreator(JwtUtils.getLoginUserId());
        aboveTheQuotaApply.setCreatorName(JwtUtils.getLoginUsername());
        aboveTheQuotaApply.setCheckStatus(AboveTheQuotaApply.CheckStatus.approve);
        aboveTheQuotaApply.setMainCabCode(aboveTheQuotaApplyForm.getMainCabCode());
        aboveTheQuotaApply.setAuditPersonId(authorityManage.getExcessAuditor());
        JsonResult<UserVO> userVOJsonResult = userClient.getUserInfoByUserId(authorityManage.getExcessAuditor());
        aboveTheQuotaApply.setAuthorityManageId(authorityManage.getId());
        if(null != userVOJsonResult && userVOJsonResult.getData() != null) {
            aboveTheQuotaApply.setAuditPerson(userVOJsonResult.getData().getNickname());
        }
        aboveTheQuotaApply.setCreditQuantity(authorityManage.getCreditQuantity());
        aboveTheQuotaApply.setCreditAmount(authorityManage.getCreditAmount());

        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
            aboveTheQuotaApply.setPracticalCreditQuantity(authorityManage.getPracticalCreditQuantity());
            aboveTheQuotaApply.setPracticalLineOfCredit(authorityManage.getPracticalLineOfCredit());
        }
        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
            aboveTheQuotaApply.setPracticalCreditQuantity(authorityMember.getPracticalCreditQuantity());
            aboveTheQuotaApply.setPracticalLineOfCredit(authorityMember.getPracticalLineOfCredit());
        }

            aboveTheQuotaApply.setRecheckAmount(authorityManage.getRecheckAmount());
        aboveTheQuotaApply.setCreditType(authorityManage.getCreditType().getValue());

        aboveTheQuotaApply.setDay(Integer.valueOf(today));
        baseMapper.insert(aboveTheQuotaApply);
        Integer totalQuantity = 0;
        if(CollectionUtils.isNotEmpty(aboveTheQuotaApplyForm.getProductDetail())){
            for (AboveTheQuotaApplyProductForm item : aboveTheQuotaApplyForm.getProductDetail()){
                ProductDetailVO productDetail = productDetailService.getProductDetailBySkuCode(item.getSkuCode());
                AuthorityMateriel authorityMateriel = authorityMaterielService.getOne(new LambdaQueryWrapper<AuthorityMateriel>().eq(AuthorityMateriel::getSkuCode, item.getSkuCode()).eq(AuthorityMateriel::getManageId, authorityManage.getId()));
                if(null == authorityMateriel){
                    throw new BusinessException("物料:"+item.getSkuCode()+"，不在权限组里面");
                }
                AboveTheQuotaApplyProduct aboveTheQuotaApplyProduct = new AboveTheQuotaApplyProduct();
                aboveTheQuotaApplyProduct.setAboveTheQuotaApplyId(aboveTheQuotaApply.getId())
                        .setSkuCode(item.getSkuCode())
                        .setQuantity(item.getQuantity() * productDetail.getQuantityPackUnit())
                        .setQuantityPack(item.getQuantity())
                        .setPackId(item.getPackId())
                        .setAboveTheQuotaApplyId(aboveTheQuotaApply.getId())
                        .setPrice(productDetail.getMarketPrice())
                        .setTotalPrice(productDetail.getMarketPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                                //.multiply(BigDecimal.valueOf(productDetail.getQuantityPackUnit())))
                        .setCabCode(item.getCabCode())
                        .setNumber(authorityMateriel.getNumber())
                        .setAmount(authorityMateriel.getAmount())
                        .setRealNumber(authorityMateriel.getRealNumber())
                        .setRealAmount(authorityMateriel.getRealAmount())
                        .setEnterpriseCode(JwtUtils.getEnterpriseCode());
                total = total.add(aboveTheQuotaApplyProduct.getTotalPrice());
                totalQuantity += aboveTheQuotaApplyProduct.getQuantity();

                //查询剩余金额 （超额金额-剩余金额算出实际授信额度）
                //CountQuota countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>().eq(CountQuota::getSkuCode, item.getSkuCode())
                //        .eq(CountQuota::getAuthorityManageId, aboveTheQuotaApplyForm.getAuthorityManageId()));
                //countQuoTotal = countQuoTotal.add(countQuota.getBalance());
                JsonResult<ProductPackVO> packVOJsonResult = enterpriseClient.getProductPackById(item.getPackId());
                if(packVOJsonResult.getCode()== Result.Code.SUCCESS.getCode()){
                    if(packVOJsonResult.getData().getBaseRate() != null){
                        //aboveTheQuotaApplyProduct.setQuantityPack(packVOJsonResult.getData().getBaseRate() * item.getQuantity());
                        aboveTheQuotaApplyProduct.setPackName(packVOJsonResult.getData().getName());
                        aboveTheQuotaApplyProduct.setPackUnitName(productDetail.getUnitName());
                        aboveTheQuotaApplyProduct.setQuantityPackUnit(packVOJsonResult.getData().getBaseRate());
                    }
                }
                aboveTheQuotaApplyProductService.save(aboveTheQuotaApplyProduct);
            }
        }
        aboveTheQuotaApply.setQuantity(totalQuantity);
        aboveTheQuotaApply.setTotalPrice(total);
        baseMapper.updateById(aboveTheQuotaApply);

        //BigDecimal difference = authorityManage.getLineOfCredit().add(total.subtract(countQuoTotal));
        //authorityManage.setPracticalLineOfCredit(difference);
        //authorityManageService.updateById(authorityManage);

        //发送初审邮件
        try {
            log.info("超额邮件发送开始");
            if (StringUtils.isNotBlank(userVOJsonResult.getData().getEmail())) {
                log.info("超额邮件发送开始: 收件人邮箱:" + userVOJsonResult.getData().getEmail());
                StringBuffer oldSpecCodeSb = new StringBuffer();
                StringBuffer productNameSb = new StringBuffer();
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("aboveTheQuotaApplyId", aboveTheQuotaApply.getId());
                List<AboveTheQuotaApplyProductVO> aboveTheQuotaApplyProductList = aboveTheQuotaApplyProductService.list4app(params);
                for (AboveTheQuotaApplyProductVO aboveTheQuotaApplyProductVO : aboveTheQuotaApplyProductList) {
                    oldSpecCodeSb.append(aboveTheQuotaApplyProductVO.getSpecCode()).append(",");
                    productNameSb.append(aboveTheQuotaApplyProductVO.getSkuName()).append(",");
                }
                oldSpecCodeSb.deleteCharAt(oldSpecCodeSb.length()-1);
                productNameSb.deleteCharAt(productNameSb.length()-1);

                String rsaData = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, aboveTheQuotaApply.getId().toString());
                //InetAddress address = InetAddress.getLocalHost();
                //MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                //mimeMessage.setFrom(new InternetAddress(mailInfo.queryInfo().get("send_account").toString()));
                //mimeMessage.addRecipient(Message.RecipientType.TO,
                //        new InternetAddress(userVOJsonResult.getData().getEmail()));
                //mimeMessage.setSubject("主题：领新超额初审申请审核");
                //StringBuffer content = new StringBuffer();
                //content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                //content.append("<p>" + aboveTheQuotaApply.getCreatorName() + "领新超额初审申请审核：</p>");
                //content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                //content.append("<p>物料名称为" + productNameSb.toString() + "。</p>");
                //content.append("<p>规格为" + oldSpecCodeSb.toString() + "。</p>");
                //content.append("<p>申请数量为" + aboveTheQuotaApply.getQuantity() + "。</p>");
                //content.append("<p>主柜编号" + aboveTheQuotaApply.getMainCabCode() + "。</p>");
                //content.append("</div>");
                //content.append("<div style='text-align:right'>");
                //content.append("<a style='background-color: #409eff; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                //        "href=http://" + address.getHostAddress() + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/firstCheckAudit?signData=" + rsaData + ">审核通过</a>");
                //content.append("<a style='background-color: #f56c6c; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                //        "href=http://" + address.getHostAddress() + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/firstCheckReject?signData=" + rsaData + ">审核驳回</a>");
                //content.append("</div>");
                //content.append("</div>");
                //mimeMessage.setContent(content.toString(), "text/html;charset=UTF-8");
                //javaMailSender.send(mimeMessage);
                //InetAddress address = InetAddress.getLocalHost();
                StringBuffer content = new StringBuffer();
                log.info("超额邮件发送开始: 本地域名:" + domain);
                content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                content.append("<p>" + aboveTheQuotaApply.getCreatorName() + "领新超额初审申请审核：</p>");
                content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                content.append("<p>物料名称为" + productNameSb.toString() + "。</p>");
                content.append("<p>规格为" + oldSpecCodeSb.toString() + "。</p>");
                content.append("<p>申请数量为" + aboveTheQuotaApply.getQuantity() + "。</p>");
                content.append("<p>主柜编号" + aboveTheQuotaApply.getMainCabCode() + "。</p>");
                content.append("</div>");
                content.append("<div style='text-align:right'>");
                content.append("<a style='background-color: #409eff; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                        "href=http://" + domain + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/firstCheckAudit?signData=" + rsaData + ">审核通过</a>");
                content.append("<a style='background-color: #f56c6c; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                        "href=http://" + domain + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/firstCheckReject?signData=" + rsaData + ">审核驳回</a>");
                content.append("</div>");
                content.append("</div>");
                HashMap map = mailInfo.queryInfo();
                String userName = map.get("send_account").toString();
                String password = map.get("email_password").toString();
                String host = map.get("smtp_server").toString();
                String port = map.get("port").toString();
                String ssl = map.get("is_ssl").toString();
                senderConfig.sendMail(userName,password,host,ssl, Integer.valueOf(port),userVOJsonResult.getData().getEmail(),"主题：领新超额初审申请审核",content.toString());

            }
            log.info("超额邮件发送结束");
        }catch (Exception e){
            log.error("发送邮件失败:" , e);
            //throw new BusinessException("发送邮件失败:"+ e.getMessage());
        }

    }

    @Override
    @Transactional
    public void firstCheck(Long id, AboveTheQuotaApply.CheckStatus checkStatus, String remark,String domain, String items) {
        AboveTheQuotaApply aboveTheQuotaApply = baseMapper.selectById(id);
        if(null == aboveTheQuotaApply){
            throw new BusinessException("超额申请记录审核失败:未查询到超额申请记录!");
        }
        //审核状态:approve(0,待初审);reject(1,初审驳回);toaudit(2,初审通过);appRCheck(3,待复审);rCheckReject(4,复审驳回);rCheckAudit(5,复审通过）
        if(!aboveTheQuotaApply.getCheckStatus().getValue().equals(0)){
            throw new BusinessException("超额申请记录审核失败:状态不是待初审状态!");
        }

        AuthorityManage authorityManage = authorityManageService.getById(aboveTheQuotaApply.getAuthorityManageId());
        if(null == authorityManage){
            throw new BusinessException("超额申请记录审核失败:权限组记录不存在!");
        }

        if(!checkStatus.getValue().equals(1) && !checkStatus.getValue().equals(2)){
            throw new BusinessException("超额申请记录审核失败:状态参数异常!");
        }

        QueryWrapper<AuthorityMember> authorityMemberQueryWrapper = new QueryWrapper<>();
        authorityMemberQueryWrapper.eq("authority_manage_id", authorityManage.getId());
        authorityMemberQueryWrapper.eq("user_id", aboveTheQuotaApply.getCreator());
        AuthorityMember authorityMember = authorityMemberService.getOne(authorityMemberQueryWrapper);
        if(null == authorityMember){
            throw new BusinessException("超额申请记录审核失败:申请人不在该权限组! 权限组名称:" + authorityManage.getName());
        }

        //if(!aboveTheQuotaApply.getAuditPersonId().equals(JwtUtils.getLoginUserId())){
        //    throw new BusinessException("超额申请记录审核失败:当前用户没有初审权限!");
        //}

        aboveTheQuotaApply.setCheckStatus(checkStatus);
        aboveTheQuotaApply.setAuditTime(LocalDateTime.now());

        Integer totalActurlQuantity = 0;
        BigDecimal totalActurlTotalPrice = new BigDecimal(0);

        QueryWrapper<AboveTheQuotaApplyProduct> aboveTheQuotaApplyProductQueryWrapper = new QueryWrapper<AboveTheQuotaApplyProduct>();
        aboveTheQuotaApplyProductQueryWrapper.eq("above_the_quota_apply_id", id);
        List<AboveTheQuotaApplyProduct> aboveTheQuotaApplyProductList = aboveTheQuotaApplyProductService.list(aboveTheQuotaApplyProductQueryWrapper);

        JSONArray jsonArray = JSONArray.parseArray(items);
        Map<Long, JSONObject> sumMap = new HashMap<>();
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = (JSONObject)jsonArray.get(i);
            sumMap.put(jsonObject.getLong("id"), jsonObject);
        }
        for (AboveTheQuotaApplyProduct aboveTheQuotaApplyProduct : aboveTheQuotaApplyProductList) {
            if(!sumMap.containsKey(aboveTheQuotaApplyProduct.getId())){
                throw new BusinessException("超额申请记录审核失败:明细提交失败!");
            }
            JSONObject jsonObject = sumMap.get(aboveTheQuotaApplyProduct.getId());
            aboveTheQuotaApplyProduct.setActurlQuantity(jsonObject.getInteger("acturlQuantity"));
            aboveTheQuotaApplyProduct.setActurlTotalPrice(jsonObject.getBigDecimal("acturlTotalPrice"));
            totalActurlQuantity = totalActurlQuantity + aboveTheQuotaApplyProduct.getActurlQuantity();
            totalActurlTotalPrice = totalActurlTotalPrice.add(aboveTheQuotaApplyProduct.getActurlTotalPrice());

            aboveTheQuotaApplyProductService.updateById(aboveTheQuotaApplyProduct);
        }

        aboveTheQuotaApply.setActurlQuantity(totalActurlQuantity);
        aboveTheQuotaApply.setActurlTotalPrice(totalActurlTotalPrice);

        //初审通过
        if(checkStatus.getValue().equals(2)){

            //如果超过复审额度 需要 复审人进行复审
            if(aboveTheQuotaApply.getActurlTotalPrice().compareTo(authorityManage.getRecheckAmount()) >=0){
                aboveTheQuotaApply.setCheckStatus(AboveTheQuotaApply.CheckStatus.appRCheck);
                aboveTheQuotaApply.setTwoAuditPersonId(authorityManage.getRecheckAmountAuditor());
                JsonResult<UserVO> userVOJsonResult = userClient.getUserInfoByUserId(authorityManage.getRecheckAmountAuditor());
                if(null != userVOJsonResult && userVOJsonResult.getData() != null) {
                    aboveTheQuotaApply.setTwoAuditPerson(userVOJsonResult.getData().getNickname());
                    //发送复审邮件
                    try {
                        if (StringUtils.isNotBlank(userVOJsonResult.getData().getEmail())) {
                            StringBuffer oldSpecCodeSb = new StringBuffer();
                            for (AboveTheQuotaApplyProduct aboveTheQuotaApplyProduct : aboveTheQuotaApplyProductList) {
                                oldSpecCodeSb.append(aboveTheQuotaApplyProduct.getSkuCode()).append(",");
                            }
                            oldSpecCodeSb.deleteCharAt(oldSpecCodeSb.length()-1);

                            String rsaData = RSAUtils.encryptByPublicKey(RSAUtils.publicKey, aboveTheQuotaApply.getId().toString());
                            //InetAddress address = InetAddress.getLocalHost();
                            //MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                            //mimeMessage.setFrom(new InternetAddress(mailInfo.queryInfo().get("send_account").toString()));
                            //mimeMessage.addRecipient(Message.RecipientType.TO,
                            //        new InternetAddress(userVOJsonResult.getData().getEmail()));
                            //mimeMessage.setSubject("主题：领新超额复审申请审核");
                            //StringBuffer content = new StringBuffer();
                            //content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                            //content.append("<p>" + aboveTheQuotaApply.getCreatorName() + "领新超额复审申请审核：</p>");
                            //content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                            //content.append("<p>物料名称为" + productNameSb.toString() + "。</p>");
                            //content.append("<p>规格为" + oldSpecCodeSb.toString() + "。</p>");
                            //content.append("<p>申请数量为" + aboveTheQuotaApply.getQuantity() + "。</p>");
                            //content.append("<p>主柜编号" + aboveTheQuotaApply.getMainCabCode() + "。</p>");
                            //content.append("</div>");
                            //content.append("<div style='text-align:right'>");
                            //content.append("<a style='background-color: #409eff; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                            //        "href=http://" + address.getHostAddress() + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/againCheckAudit?signData=" + rsaData + ">审核通过</a>");
                            //content.append("<a style='background-color: #f56c6c; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                            //        "href=http://" + address.getHostAddress() + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/againCheckReject?signData=" + rsaData + ">审核驳回</a>");
                            //content.append("</div>");
                            //content.append("</div>");
                            //mimeMessage.setContent(content.toString(), "text/html;charset=UTF-8");
                            //javaMailSender.send(mimeMessage);

                            //InetAddress address = InetAddress.getLocalHost();
                            StringBuffer content = new StringBuffer();
                            content.append("<div style='font-size: 18px;min-height: 180px;height: auto;min-height:350px;background-color: #f5f5f7;box-shadow: 0 0 10px 3px #0000001a;border-radius: 20px;box-sizing: border-box;padding:30px;margin: 20px;'>");
                            content.append("<p>" + aboveTheQuotaApply.getCreatorName() + "领新超额复审申请审核：</p>");
                            content.append("<div style='text-align: left;min-height: 180px; margin: 10px 0;height: auto; padding-left: 2em;'>");
                            content.append("<p>物料编码为" + oldSpecCodeSb.toString() + "。</p>");
                            content.append("<p>申请数量为" + aboveTheQuotaApply.getActurlQuantity() + "。</p>");
                            content.append("<p>主柜编号" + aboveTheQuotaApply.getMainCabCode() + "。</p>");
                            content.append("</div>");
                            content.append("<div style='text-align:right'>");
                            content.append("<a style='background-color: #409eff; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                                    "href=http://" + domain + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/againCheckAudit?signData=" + rsaData + ">审核通过</a>");
                            content.append("<a style='background-color: #f56c6c; padding: 8px 12px; display: inline-block; border-radius: 10px;text-decoration: none; color: #fff; margin: 0 10px;' " +
                                    "href=http://" + domain + ":9300/enterprisecab/cabinet/admin/aboveTheQuotaApply/againCheckReject?signData=" + rsaData + ">审核驳回</a>");
                            content.append("</div>");
                            content.append("</div>");
                            HashMap map = mailInfo.queryInfo();
                            String userName = map.get("send_account").toString();
                            String password = map.get("email_password").toString();
                            String host = map.get("smtp_server").toString();
                            String port = map.get("port").toString();
                            String ssl = map.get("is_ssl").toString();
                            senderConfig.sendMail(userName,password,host,ssl, Integer.valueOf(port),userVOJsonResult.getData().getEmail(),"主题：领新超额复审申请审核",content.toString());

                        }
                    }catch (Exception e){
                        log.error("发送邮件失败:" , e);
                        //throw new BusinessException("发送邮件失败:"+ e.getMessage());
                    }
                }
            }else {

                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                    aboveTheQuotaApply.setPracticalCreditQuantity(authorityManage.getPracticalCreditQuantity());
                    aboveTheQuotaApply.setPracticalLineOfCredit(authorityManage.getPracticalLineOfCredit());
                }
                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                    aboveTheQuotaApply.setPracticalCreditQuantity(authorityMember.getPracticalCreditQuantity());
                    aboveTheQuotaApply.setPracticalLineOfCredit(authorityMember.getPracticalLineOfCredit());
                }

                //更新权限表 实际授信总额
                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                    if(null == authorityManage.getCreditAmount()){
                        authorityManage.setCreditAmount(new BigDecimal(0));
                    }
                    if(null == authorityManage.getCreditQuantity()){
                        authorityManage.setCreditQuantity(0);
                    }
                    //按数量
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                        authorityManage.setPracticalCreditQuantity(authorityManage.getPracticalCreditQuantity() + aboveTheQuotaApply.getActurlQuantity());
                    }
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                        authorityManage.setPracticalLineOfCredit(authorityManage.getPracticalLineOfCredit().add(aboveTheQuotaApply.getActurlTotalPrice()));
                    }
                }

                authorityManageService.updateById(authorityManage);

                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                    if(null == authorityMember.getPracticalLineOfCredit()){
                        authorityMember.setPracticalLineOfCredit(new BigDecimal(0));
                    }
                    if(null == authorityMember.getPracticalCreditQuantity()){
                        authorityMember.setPracticalCreditQuantity(0);
                    }
                    //按数量
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                        authorityMember.setPracticalCreditQuantity(authorityMember.getPracticalCreditQuantity() + aboveTheQuotaApply.getActurlQuantity());
                    }
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                        authorityMember.setPracticalLineOfCredit(authorityMember.getPracticalLineOfCredit().add(aboveTheQuotaApply.getActurlTotalPrice()));
                    }
                    authorityMemberService.updateById(authorityMember);
                }


                for (AboveTheQuotaApplyProduct aboveTheQuotaApplyProduct : aboveTheQuotaApplyProductList) {
                    CountQuota countQuota = null;
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)) {//共享金额或者共享数量
                        countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                                .eq(CountQuota::getSkuCode, aboveTheQuotaApplyProduct.getSkuCode()));
                    } else {
                        countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                                .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                                .eq(CountQuota::getReceiverId, aboveTheQuotaApply.getCreator())
                                .eq(CountQuota::getSkuCode, aboveTheQuotaApplyProduct.getSkuCode()));
                    }

                    if(countQuota!=null){

                        //查询权限物料表，修改物料表限额
                        //按金额
                        if (authorityManage.getCreditType().getValue() == 0) {
                            //剩余可领金额
                            BigDecimal surplusAmount = countQuota.getBalance().add(aboveTheQuotaApplyProduct.getActurlTotalPrice());
                            //权限组的授信方式
                            //组员共享领用金额
                            if (authorityManage.getCreditWay().name().equals("share")) {
                                List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                        .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                                        .eq(CountQuota::getCreditWay, CountQuota.CreditWay.share)
                                        .eq(CountQuota::getSkuCode, aboveTheQuotaApplyProduct.getSkuCode()));
                                for (CountQuota countQuotaItem : countQuotaList) {
                                    countQuotaItem.setBalance(surplusAmount);
                                    countQuotaService.updateById(countQuotaItem);
                                }
                            }
                            //组员独立授信领用金额
                            if (authorityManage.getCreditWay().name().equals("independent")) {
                                //额度评估周期
                                // 如果授信类型是金额
                                countQuota.setBalance(surplusAmount);
                                countQuotaService.updateById(countQuota);
                            }
                        }

                        //按数量
                        if (authorityManage.getCreditType().getValue() == 1) {
                            //剩余可领数量
                            Integer surplusQuantity = countQuota.getResidualQuantity() + aboveTheQuotaApplyProduct.getActurlQuantity();

                            if(authorityManage.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                                List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                        .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                                        .eq(CountQuota::getCreditWay, CountQuota.CreditWay.shareQuantity)
                                        .eq(CountQuota::getSkuCode,aboveTheQuotaApplyProduct.getSkuCode()));
                                if(CollectionUtil.isNotEmpty(countQuotaList)){
                                    for (CountQuota countQuotaItem:countQuotaList){
                                        countQuotaItem.setResidualQuantity(surplusQuantity);
                                        countQuotaService.updateById(countQuotaItem);
                                    }
                                }
                            }
                            if(authorityManage.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                                //额度评估周期
                                // 如果授信类型是数量
                                countQuota.setResidualQuantity(surplusQuantity);
                                countQuotaService.updateById(countQuota);
                            }
                        }

                    }

                }

            }

        }

        ////初审驳回
        //if(checkStatus.getValue().equals(1)){
        //
        //}
        aboveTheQuotaApply.setCreditQuantity(authorityManage.getCreditQuantity());
        aboveTheQuotaApply.setCreditAmount(authorityManage.getCreditAmount());
        baseMapper.updateById(aboveTheQuotaApply);

    }

    @Override
    @Transactional
    public void againCheck(Long id, AboveTheQuotaApply.CheckStatus checkStatus, String remark, String items) {
        AboveTheQuotaApply aboveTheQuotaApply = baseMapper.selectById(id);
        if(null == aboveTheQuotaApply){
            throw new BusinessException("超额申请记录审核失败:未查询到超额申请记录!");
        }
        //审核状态:approve(0,待初审);reject(1,初审驳回);toaudit(2,初审通过);appRCheck(3,待复审);rCheckReject(4,复审驳回);rCheckAudit(5,复审通过）
        if(!aboveTheQuotaApply.getCheckStatus().getValue().equals(3)){
            throw new BusinessException("超额申请记录审核失败:状态不是待复审状态!");
        }

        AuthorityManage authorityManage = authorityManageService.getById(aboveTheQuotaApply.getAuthorityManageId());
        if(null == authorityManage){
            throw new BusinessException("超额申请记录审核失败:权限组记录不存在!");
        }

        if(!checkStatus.getValue().equals(4) && !checkStatus.getValue().equals(5)){
            throw new BusinessException("超额申请记录审核失败:状态参数异常!");
        }

        QueryWrapper<AuthorityMember> authorityMemberQueryWrapper = new QueryWrapper<>();
        authorityMemberQueryWrapper.eq("authority_manage_id", authorityManage.getId());
        authorityMemberQueryWrapper.eq("user_id", aboveTheQuotaApply.getCreator());
        AuthorityMember authorityMember = authorityMemberService.getOne(authorityMemberQueryWrapper);
        if(null == authorityMember){
            throw new BusinessException("超额申请记录审核失败:申请人不在该权限组! 权限组名称:" + authorityManage.getName());
        }

        //if(!aboveTheQuotaApply.getTwoAuditPersonId().equals(JwtUtils.getLoginUserId())){
        //    throw new BusinessException("超额申请记录审核失败:当前用户没有初审权限!");
        //}

        aboveTheQuotaApply.setCheckStatus(checkStatus);
        aboveTheQuotaApply.setTwoAuditTime(LocalDateTime.now());

        Integer totalActurlQuantity = 0;
        BigDecimal totalActurlTotalPrice = new BigDecimal(0);
        QueryWrapper<AboveTheQuotaApplyProduct> aboveTheQuotaApplyProductQueryWrapper = new QueryWrapper<AboveTheQuotaApplyProduct>();
        aboveTheQuotaApplyProductQueryWrapper.eq("above_the_quota_apply_id", id);
        List<AboveTheQuotaApplyProduct> aboveTheQuotaApplyProductList = aboveTheQuotaApplyProductService.list(aboveTheQuotaApplyProductQueryWrapper);

        JSONArray jsonArray = JSONArray.parseArray(items);
        Map<Long, JSONObject> sumMap = new HashMap<>();
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = (JSONObject)jsonArray.get(i);
            sumMap.put(jsonObject.getLong("id"), jsonObject);
        }
        for (AboveTheQuotaApplyProduct aboveTheQuotaApplyProduct : aboveTheQuotaApplyProductList) {
            if(!sumMap.containsKey(aboveTheQuotaApplyProduct.getId())){
                throw new BusinessException("超额申请记录审核失败:明细提交失败!");
            }
            JSONObject jsonObject = sumMap.get(aboveTheQuotaApplyProduct.getId());
            aboveTheQuotaApplyProduct.setActurlQuantity(jsonObject.getInteger("acturlQuantity"));
            aboveTheQuotaApplyProduct.setActurlTotalPrice(jsonObject.getBigDecimal("acturlTotalPrice"));
            totalActurlQuantity = totalActurlQuantity + aboveTheQuotaApplyProduct.getActurlQuantity();
            totalActurlTotalPrice = totalActurlTotalPrice.add(aboveTheQuotaApplyProduct.getActurlTotalPrice());

            aboveTheQuotaApplyProductService.updateById(aboveTheQuotaApplyProduct);
        }

        aboveTheQuotaApply.setActurlQuantity(totalActurlQuantity);
        aboveTheQuotaApply.setActurlTotalPrice(totalActurlTotalPrice);

        //复审通过
        if(checkStatus.getValue().equals(5)){

            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                aboveTheQuotaApply.setPracticalCreditQuantity(authorityManage.getPracticalCreditQuantity());
                aboveTheQuotaApply.setPracticalLineOfCredit(authorityManage.getPracticalLineOfCredit());
            }
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                aboveTheQuotaApply.setPracticalCreditQuantity(authorityMember.getPracticalCreditQuantity());
                aboveTheQuotaApply.setPracticalLineOfCredit(authorityMember.getPracticalLineOfCredit());
            }

            //更新权限表 实际授信总额
            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                if(null == authorityManage.getCreditAmount()){
                    authorityManage.setCreditAmount(new BigDecimal(0));
                }
                if(null == authorityManage.getCreditQuantity()){
                    authorityManage.setCreditQuantity(0);
                }
                //按数量
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                    authorityManage.setPracticalCreditQuantity(authorityManage.getPracticalCreditQuantity() + aboveTheQuotaApply.getActurlQuantity());
                }
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                    authorityManage.setPracticalLineOfCredit(authorityManage.getPracticalLineOfCredit().add(aboveTheQuotaApply.getActurlTotalPrice()));
                }
            }

            authorityManageService.updateById(authorityManage);

            if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                if(null == authorityMember.getPracticalLineOfCredit()){
                    authorityMember.setPracticalLineOfCredit(new BigDecimal(0));
                }
                if(null == authorityMember.getPracticalCreditQuantity()){
                    authorityMember.setPracticalCreditQuantity(0);
                }
                //按数量
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)) {
                    authorityMember.setPracticalCreditQuantity(authorityMember.getPracticalCreditQuantity() + aboveTheQuotaApply.getActurlQuantity());
                }
                if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)) {
                    authorityMember.setPracticalLineOfCredit(authorityMember.getPracticalLineOfCredit().add(aboveTheQuotaApply.getActurlTotalPrice()));
                }
                authorityMemberService.updateById(authorityMember);
            }


            for (AboveTheQuotaApplyProduct aboveTheQuotaApplyProduct : aboveTheQuotaApplyProductList) {
                CountQuota countQuota = null;
                if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)) {//共享金额或者共享数量
                    countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                            .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                            .eq(CountQuota::getSkuCode, aboveTheQuotaApplyProduct.getSkuCode()));
                } else {
                    countQuota = countQuotaService.getOne(new LambdaQueryWrapper<CountQuota>()
                            .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                            .eq(CountQuota::getReceiverId, aboveTheQuotaApply.getCreator())
                            .eq(CountQuota::getSkuCode, aboveTheQuotaApplyProduct.getSkuCode()));
                }

                if(countQuota!=null){

                    //查询权限物料表，修改物料表限额
                    //按金额
                    if (authorityManage.getCreditType().getValue() == 0) {
                        //剩余可领金额
                        BigDecimal surplusAmount = countQuota.getBalance().add(aboveTheQuotaApplyProduct.getActurlTotalPrice());
                        //权限组的授信方式
                        //组员共享领用金额
                        if (authorityManage.getCreditWay().name().equals("share")) {
                            List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                    .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                                    .eq(CountQuota::getCreditWay, CountQuota.CreditWay.share)
                                    .eq(CountQuota::getSkuCode, aboveTheQuotaApplyProduct.getSkuCode()));
                            for (CountQuota countQuotaItem : countQuotaList) {
                                countQuotaItem.setBalance(surplusAmount);
                                countQuotaService.updateById(countQuotaItem);
                            }
                        }
                        //组员独立授信领用金额
                        if (authorityManage.getCreditWay().name().equals("independent")) {
                            //额度评估周期
                            // 如果授信类型是金额
                            countQuota.setBalance(surplusAmount);
                            countQuotaService.updateById(countQuota);
                        }
                    }

                    //按数量
                    if (authorityManage.getCreditType().getValue() == 1) {
                        //剩余可领数量
                        Integer surplusQuantity = countQuota.getResidualQuantity() + aboveTheQuotaApplyProduct.getActurlQuantity();

                        if(authorityManage.getCreditWay().name().equals("shareQuantity")){ //组员共享领用数量
                            List<CountQuota> countQuotaList = countQuotaService.list(new LambdaQueryWrapper<CountQuota>()
                                    .eq(CountQuota::getAuthorityManageId, authorityManage.getId())
                                    .eq(CountQuota::getCreditWay, CountQuota.CreditWay.shareQuantity)
                                    .eq(CountQuota::getSkuCode,aboveTheQuotaApplyProduct.getSkuCode()));
                            if(CollectionUtil.isNotEmpty(countQuotaList)){
                                for (CountQuota countQuotaItem:countQuotaList){
                                    countQuotaItem.setResidualQuantity(surplusQuantity);
                                    countQuotaService.updateById(countQuotaItem);
                                }
                            }
                        }
                        if(authorityManage.getCreditWay().name().equals("independentQuantity")){//组员独立授信领用数量
                            //额度评估周期
                            // 如果授信类型是数量
                            countQuota.setResidualQuantity(surplusQuantity);
                            countQuotaService.updateById(countQuota);
                        }
                    }

                }

            }

        }

        ////初审驳回
        //if(checkStatus.getValue().equals(1)){
        //
        //}
        aboveTheQuotaApply.setCreditQuantity(authorityManage.getCreditQuantity());
        aboveTheQuotaApply.setCreditAmount(authorityManage.getCreditAmount());
        baseMapper.updateById(aboveTheQuotaApply);
    }

    @Override
    public AboveTheQuotaApplyVO getAboveTheQuotaApplyVOInfo(Long aboveTheQuotaApplyId) {
        AboveTheQuotaApplyVO quotaApplyVO = baseMapper.get4appById(aboveTheQuotaApplyId);

        //根据领新申请单的主柜编号查询售刀副柜
        List<Cabinet> cabinetVOList = cabinetService.list(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getBelongCabinet, quotaApplyVO.getMainCabCode())
                .eq(Cabinet::getCabinetNature,1));
        Map<String, Object> params = new HashMap<>();
        params.put("aboveTheQuotaApplyId",aboveTheQuotaApplyId);
        List<AboveTheQuotaApplyProductVO> productVOList = aboveTheQuotaApplyProductService.list4app(params);
        for (AboveTheQuotaApplyProductVO productItem : productVOList){
            for (Cabinet cabinetItem : cabinetVOList){
                List<CellInventorySpace> inventorySpaceList = cellInventorySpaceService.list(new LambdaQueryWrapper<CellInventorySpace>()
                        .eq(CellInventorySpace::getSkuCode, productItem.getSkuCode())
                        .eq(CellInventorySpace::getCabCode,cabinetItem.getCode()));
                productItem.setInventorySpaceList(inventorySpaceList);
            }
        }
        quotaApplyVO.setProductList(productVOList);
        return quotaApplyVO;
    }
}
